package com.cloud.custom.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.cloud.custom.api.entity.CustomBizConfig;
import com.cloud.custom.api.entity.CustomBizFields;
import com.cloud.custom.api.mapper.CustomBizConfigMapper;
import com.cloud.custom.api.mapper.CustomBizFieldsMapper;
import com.cloud.custom.api.service.CustomBizConfigService;
import com.cloud.custom.common.consts.CustomConsts;
import com.cloud.custom.common.exception.BizException;
import com.cloud.custom.common.utils.SessionHelper;
import com.cloud.custom.common.utils.SqlParserHelper;
import com.cloud.custom.tasklist.entity.TaskListField;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class CustomBizConfigServiceImpl implements CustomBizConfigService {

	@Autowired
	private CustomBizConfigMapper customBizConfigMapper;

	@Autowired
	private CustomBizFieldsMapper customBizFieldsMapper;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<CustomBizConfig> listCustomBizs() {
		Example example = new Example(CustomBizConfig.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("enableFlag", 1);
		example.orderBy("bizId");
		return customBizConfigMapper.selectByExample(example);
	}

	@Override
	public CustomBizConfig addCustomBiz(CustomBizConfig biz) {
		biz.setCreateHuman(SessionHelper.get().getHumanName());
		biz.setCreateTime(new Date());
		biz.setEnableFlag(1);
		customBizConfigMapper.insert(biz);
		return biz;
	}

	@Override
	public void deleteCustomBiz(Integer bizId) {
		customBizConfigMapper.deleteByPrimaryKey(bizId);
	}

	@Override
	public boolean existsBizId(Integer bizId) {
		return customBizConfigMapper.existsWithPrimaryKey(bizId);
	}

	@Override
	public List<String> loadCustomTable() {
		List<String> tables = jdbcTemplate.queryForList("show tables", String.class);
		return tables.stream().filter((tableName) -> tableName.toLowerCase().startsWith("rec_"))
				.collect(Collectors.toList());

	}

	@Override
	public List<CustomBizFields> loadCustomTableFiles(String tableName, Integer bizId) {
		List<CustomBizFields> results = null;
		if (StringUtils.isEmpty(tableName)) {
			Example example = new Example(CustomBizFields.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("bizId", bizId);
			results = customBizFieldsMapper.selectByExample(example);
		} else {
			StringBuilder sql = new StringBuilder("select * from ").append(tableName).append(" where 1 = 2 ");
			List<TaskListField> fields = SqlParserHelper.listFieldInfoBySQL(sql.toString(), jdbcTemplate);
			results = new ArrayList<CustomBizFields>();
			List<String> columnNames = new ArrayList<String>(fields.size());
			for (TaskListField f : fields) {
				columnNames.add(f.getColumnName().toLowerCase());
			}
			for (String fieldName : CustomConsts.DFT_COLUMN_LIST) {
				if (!columnNames.contains(fieldName)) {
					throw new BizException(500, " 业务表必须要包含字段：" + fieldName);
				}
			}
			int i = 1;
			for (TaskListField f : fields) {
				if (!CustomConsts.DFT_COLUMN_LIST.contains(f.getFieldName())) {
					CustomBizFields r = new CustomBizFields();
					r.setBizId(bizId);
					r.setColumnName(f.getColumnName());
					r.setDisplayName(f.getColumnName());
					r.setDataTypeId(f.getFieldType());
					r.setDataTypeName(f.getFieldTypeName());
					r.setColumnClassName(f.getSetColumnClassName());
					r.setDisplayOrder(i++);
					results.add(r);
				}
			}
		}
		return results;
	}

	@Override
	public void saveCustomFields(Integer bizId, String tableName, List<CustomBizFields> fields) {
		CustomBizConfig bizConfig = customBizConfigMapper.selectByPrimaryKey(bizId);
		bizConfig.setTableName(tableName);
		customBizConfigMapper.updateByPrimaryKey(bizConfig);
		Example example = new Example(CustomBizFields.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("bizId", bizId);
		customBizFieldsMapper.deleteByExample(example);
		for (CustomBizFields field : fields) {
			customBizFieldsMapper.insert(field);
		}
	}

	@Override
	public CustomBizConfig load(Integer bizId) {
		return customBizConfigMapper.selectByPrimaryKey(bizId);
	}

	@Override
	public List<String> loadFieldName(Integer bizId) {
		return jdbcTemplate.queryForList("select display_name from custom_biz_fields where biz_id = ?", String.class, bizId);
	}

}
